import React, { useEffect, useState } from 'react'
import { Table, Button, notification } from 'antd';
import axios from 'axios';
export default function NewsDraft(props) {
    // 草稿箱列表数据
    const [auditDataSource, setAuditDataSource] = useState([])
    // 解构用户信息
    const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))

    // 获取草稿箱数据
    useEffect(() => {
        const roleObj = {
            "1": "superadmin",
            "2": "admin",
            "3": "editor"
        }

        axios.get(`/news?auditState=1&_expand=category`).then(res => {
            const list = res.data
            setAuditDataSource(roleObj[roleId] === "superadmin" ? list : [
                ...list.filter(item => item.author === username),
                ...list.filter(item => item.region === region && roleObj[item.roleId] === "editor")
            ])
        }).catch(err => console.log(err))
    }, [roleId, region, username])
    // 列表头
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: '新闻标题',
            dataIndex: 'title',
            render: (title, item) => {
                return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
            }

        },
        {
            title: '作者',
            dataIndex: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render: (category) => {
                return category.title
            }
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button type="primary" onClick={() => clickAudit(item, 2, 1)} style={{ marginRight: '10px' }}>通过</Button>
                    <Button danger onClick={() => clickAudit(item, 3, 0)}>驳回</Button>
                </div>
            }
        },
    ];

    // 点击审核操作
    const clickAudit = (item, auditState, publishState) => {
        setAuditDataSource(auditDataSource.filter(data => data.id !== item.id))
        axios.patch(`/news/${item.id}`, {
            auditState,
            publishState
        }).then(res => {
            notification.info({
                message: `通知`,
                description: '您可以到[审核管理/审核列表]中查看您的新闻的审核状态',
                placement: 'bottomRight'
            })
        })

    }

    return (
        <div>
            <Table dataSource={auditDataSource} columns={columns}
                pagination={{ pageSize: 5 }}
                rowKey={item => item.id}
            />
        </div>
    )
}
